package com.erp.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.Arrays;
import java.util.List;

public class Realm extends AuthorizingRealm {
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //1.获取登录用户名
        String username = (String) token.getPrincipal();
        //2.以用户名为条件查询mysql数据库,得到用户对象
        //模拟数据
        Employee employee = new Employee();
        employee.setUsername("xiaoluo");
        employee.setPassword("123");

        //封装成一个认证info对象
        //判断用户是否为空
        if (employee!=null){
            return new SimpleAuthenticationInfo(
                    employee,
                    employee.getPassword(),
                    super.getName()
            );
        }
        return null;
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取当前用户对象
        Employee employee = (Employee)principalCollection.getPrimaryPrincipal();

        //以用户id查询数据库,判断该角色/用户是否拥有权限  模拟
        List<String> roles= Arrays.asList("seller");
        List<String> permissions= Arrays.asList("customer:list","customer:save");

        //封装到info对象
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRoles(roles);
        info.addStringPermissions(permissions);

        return info;
    }
}
